using Microsoft.AspNetCore.DataProtection;
using Senparc.CO2NET;
using Senparc.CO2NET.RegisterServices;
using Senparc.Weixin.Entities;
using Senparc.Weixin;
using Senparc.Weixin.RegisterServices;
using Single.AppCore;
using Single.Autofac;
using Single.Core.Service;
using Single.WebApp.Components;
using System.Text.Encodings.Web;
using System.Text.Unicode;

namespace Single.WebApp
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            builder.Register();

            builder.Services.AddAuthentication(WorkController.AuthScheme, "/work/home/authorize", false, ServiceResult.Serialize(false, data: "logout"));
            builder.Services.AddDataProtection().PersistKeysToFileSystem(new DirectoryInfo(GlobalApp.GetPhysicalPath("/tempKeys")));
            builder.Services.AddMemoryCache();
            builder.Services.AddSession();
            builder.Services.AddRazorPages().AddRazorRuntimeCompilation();
            builder.Services.AddControllersWithViews(m => { m.Filters.Add(typeof(WorkExceptionFilter)); }).AddRazorRuntimeCompilation();

            builder.Services.AddHttpContextAccessor();
            builder.Services.AddSingleton(HtmlEncoder.Create(UnicodeRanges.All));

            builder.Services.AddSenparcGlobalServices(builder.Configuration);
            builder.Services.AddSenparcWeixinServices(builder.Configuration);

            builder.Host.UseAutofacExtensions();
            builder.WebHost.ConfigureKestrel((context, options) => { options.Limits.MaxRequestBodySize = long.MaxValue; });

            var app = builder.Build();

            app.UseGlobalServices();

            if (true || app.Environment.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseSession();
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();

            IRegisterService register = RegisterService.Start().UseSenparcGlobal(false, null);
            register.UseSenparcWeixin(new SenparcWeixinSetting());

            app.MapControllerRoute("default", "{area=work}/{controller=home}/{action=index}");
            app.MapControllerRoute("areas", "{area:exists}/{controller=home}/{action=index}");

            app.Run();
        }
    }
}